/*
 * TileSet.java
 *
 * Copyright (C) 2012 Matt Falkoski
 *
 *   This program is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *    the Free Software Foundation, either version 3 of the License, or
 *    (at your option) any later version.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU General Public License for more details.
 *
 *    You should have received a copy of the GNU General Public License
 *    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package com.falko.android.pinhead;

import java.io.IOException;
import java.io.InputStream;

import javax.microedition.khronos.opengles.GL10;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

public class TileSet {

	public TileSet() {
		this(0, 0, 0, 0, 1);
	}
	
	public TileSet(int tileWidth, int tileHeight, int width, int height,
			int firstGID) {
		texture_ = new Texture();
		tileWidth_ = tileWidth;
		tileHeight_ = tileHeight;
		width_ = width;
		height_ = height;
		firstGID_ = firstGID;
	}

	public void load(Context context, GL10 gl) {
		if (texture_.resource == -1) {
			return;
		}

		InputStream is = context.getResources().openRawResource(
				texture_.resource);
		Bitmap bitmap;
		try {
			bitmap = BitmapFactory.decodeStream(is);
		} finally {
			try {
				is.close();
			} catch (IOException e) {
				e.printStackTrace();
				// Ignore.
			}
		}
		texture_.loaded = false;
		Utils.loadTexture(gl, bitmap, texture_);
	}

	public void delete(GL10 gl) {
		Utils.deleteTexture(gl, texture_);
	}

	public void GIDToUV(long GID, float[][] uv) {

		if (GID < firstGID_) {
			uv = null; // Should prolly throw an error
			return;
		}

		int width = width_ * tileWidth_;
		int height = height_ * tileHeight_;
		
		//TODO: check and clear rotation flags
		// for now, assume no rotation
		
		final long gid = GID - 1;// zero based array
		final float y = (gid/ width_) * tileHeight_;
		final float x = (gid % width_) * tileWidth_;
		
		float[] uv0 = { x  / width, y  / height };
		float[] uv1 = { x / width, (y + tileHeight_) / height };
		float[] uv2 = { (x + tileWidth_) / width, (y + tileHeight_) / height };
		float[] uv3 = { (x + tileWidth_) / width, y / height };
		
		uv[0] = uv0;
		uv[1] = uv1;
		uv[2] = uv2;
		uv[3] = uv3;
	}

	public int tileWidth_; // pixels
	public int tileHeight_;// pixels
	public int width_; // in tiles;
	public int height_; // in tiles
	private int firstGID_ = 1; //test hack
	public Texture texture_;
}
